package com.bw.common.mvi

import android.graphics.Color
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import com.blankj.utilcode.util.BarUtils
import com.bw.common.mvi.BaseViewModel
import kotlinx.coroutines.launch

abstract class BaseActivity<V : ViewBinding,VM : BaseViewModel<*, *>> : AppCompatActivity() {

    protected lateinit var vm : VM
    abstract fun createVM():VM
    protected val inflate : LayoutInflater by lazy { LayoutInflater.from(this) }
    protected lateinit var v : V

    abstract fun initView()

    abstract fun initData()

    abstract fun bindState()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            window.decorView.systemUiVisibility = (
                    View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                            or View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR)
        }
        vm  = createVM()
        v = createViewBinding() as V
        setContentView(v.root)
        BarUtils.addMarginTopEqualStatusBarHeight(v.root)
        BarUtils.setStatusBarColor(this, Color.WHITE)
        initStateFlow()
        initView()
        bindState()
        initData()
    }

    abstract fun createViewBinding():ViewBinding

    fun initStateFlow(){
        lifecycleScope.launch{
            repeatOnLifecycle(Lifecycle.State.STARTED){
                vm.mutableContainer.requestStateFlow.collect{
                    if (it.request){
                        showDialog()
                    }else if (it.complate){
                        hideDialog()
                    }else if (it.erro){
                        showEmptyView()
                    }
                }
            }
        }
    }

    fun showDialog(){
        log("showDialog")
    }
    fun hideDialog(){
        log("hideDialog")
    }
    fun showEmptyView(){
        log("showEmptyView")
    }

    fun log(msg : String){
        Log.e("LIJIANG--",msg)
    }

}